<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>文件上传</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#64748b',
                        success: '#10b981',
                        danger: '#ef4444',
                        warning: '#f59e0b',
                        info: '#06b6d4',
                        light: '#f8fafc',
                        dark: '#1e293b',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .upload-area {
                @apply border-2 border-dashed border-secondary/50 rounded-xl p-6 md:p-8 transition-all duration-300 hover:border-primary hover:bg-primary/5;
            }

            .upload-area.active {
                @apply border-primary bg-primary/10;
            }

            .file-item {
                @apply flex items-center justify-between p-3 md:p-4 bg-white rounded-lg shadow-sm mb-2.5 md:mb-3 transition-all duration-300 hover:shadow-md;
            }

            .progress-bar {
                @apply h-1.5 md:h-2 bg-gray-200 rounded-full overflow-hidden;
            }

            .progress-value {
                @apply h-full bg-primary rounded-full transition-all duration-300 ease-out;
            }

            .btn {
                @apply px-3.5 py-1.5 rounded-lg font-medium transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 text-sm md:text-base;
            }

            .btn-primary {
                @apply bg-primary text-white hover:bg-primary/90 focus:ring-primary/50;
            }

            .btn-secondary {
                @apply bg-secondary text-white hover:bg-secondary/90 focus:ring-secondary/50;
            }

            .btn-danger {
                @apply bg-danger text-white hover:bg-danger/90 focus:ring-danger/50;
            }

            .btn-success {
                @apply bg-success text-white hover:bg-success/90 focus:ring-success/50;
            }
            .file-item h4[title]:hover::after {
                content: attr(title);
                position: absolute;
                left: 100%;
                top: 50%;
                transform: translateY(-50%);
                white-space: nowrap;
                background-color: rgba(0, 0, 0, 0.7);
                color: #fff;
                padding: 5px 10px;
                border-radius: 3px;
                pointer-events: none;
                z-index: 10;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen font-inter text-dark">
<div class="container mx-auto px-3 py-8 md:py-12 max-w-4xl">
    <!-- 页面标题 -->
<!--    <div class="text-center mb-6 md:mb-10">-->
<!--        <h1 class="text-[clamp(1.5rem,4vw,2.25rem)] font-bold text-dark mb-2.5">文件上传</h1>-->
<!--        <p class="text-gray-600 max-w-2xl mx-auto text-sm md:text-base">-->
<!--            上传文件到服务器，支持拖拽和点击上传，上传过程中可查看进度</p>-->
<!--    </div>-->

    <!-- 文件上传区域 -->
    <div class="bg-white rounded-2xl shadow-lg p-6 md:p-8 mb-6 md:mb-8">
        <div id="upload-area" class="upload-area text-center">
            <div class="mb-4">
                <i class="fa fa-cloud-upload text-4xl md:text-5xl text-primary/70"></i>
            </div>
            <h3 class="text-lg md:text-xl font-semibold mb-2">拖拽文件到此处上传</h3>
            <p class="text-gray-500 mb-5 md:mb-6">或者</p>
            <label for="file-input" class="btn btn-primary inline-flex items-center">
                <i class="fa fa-plus mr-2"></i>选择文件
            </label>
            <input id="file-input" type="file"  class="hidden">
            <p class="text-gray-400 text-xs md:text-sm mt-4">仅支持上传 /图片/pdf/文档/表格</p>
        </div>
    </div>

    <!-- 文件列表 -->
    <div class="bg-white rounded-2xl shadow-lg p-6 md:p-8">
        <div class="flex justify-between items-center mb-5">
            <h2 class="text-lg md:text-xl font-semibold">已选择的文件</h2>
            <button id="clear-files" class="btn btn-secondary text-xs md:text-sm">
                <i class="fa fa-trash-o mr-1"></i>清空列表
            </button>
        </div>

        <!-- 文件列表区域 -->
        <div id="file-list" class="space-y-2.5 md:space-y-3">
            <div class="text-center py-8 md:py-10 text-gray-400">
                <i class="fa fa-file-o text-3xl md:text-4xl mb-2.5 md:mb-3"></i>
                <p class="text-sm md:text-base">暂无上传的文件</p>
            </div>
        </div>

        <!-- 上传按钮 -->
        <div id="upload-container" class="mt-6 md:mt-8 text-center">
            <button id="upload-files"
                    class="btn btn-primary px-6 py-2.5 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                <i class="fa fa-upload mr-2"></i>开始上传
            </button>
        </div>
    </div>
</div>

<!-- 上传结果通知 -->
<div id="notification"
     class="fixed top-4 left-1/2 transform -translate-x-1/2 bg-white rounded-lg shadow-lg p-3 md:p-4 transition-all duration-300 z-50 max-w-xs opacity-0 translate-y-[-20px] break-words whitespace-normal">
    <div class="flex items-start">
        <div id="notification-icon" class="mr-2.5 md:mr-3 text-lg md:text-xl"></div>
        <div class="flex-1">
            <h4 id="notification-title" class="font-bold text-sm md:text-base text-gray-800"></h4>
            <p id="notification-message" class="font-bold text-sm md:text-sm text-gray-700 mt-1 max-w-[30ch] whitespace-pre-wrap"></p>
        </div>
        <button id="close-notification" class="ml-3 text-gray-400 hover:text-gray-600">
            <i class="fa fa-times"></i>
        </button>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const uploadArea = document.getElementById('upload-area');
        const fileInput = document.getElementById('file-input');
        const fileList = document.getElementById('file-list');
        const uploadFilesBtn = document.getElementById('upload-files');
        const clearFilesBtn = document.getElementById('clear-files');
        const uploadContainer = document.getElementById('upload-container');
        const notification = document.getElementById('notification');
        const notificationIcon = document.getElementById('notification-icon');
        const notificationTitle = document.getElementById('notification-title');
        const notificationMessage = document.getElementById('notification-message');
        const closeNotification = document.getElementById('close-notification');

        // 存储文件状态：{ name, size, status: 'pending' | 'uploading' | 'completed' }
        let selectedFiles = [];

        // 拖放事件处理
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            uploadArea.classList.add('active');
        }

        function unhighlight() {
            uploadArea.classList.remove('active');
        }

        // 处理拖放文件
        uploadArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleFiles(files);
        }

        // 处理文件选择
        fileInput.addEventListener('change', function () {
            handleFiles(this.files);
            this.value = '';
        });

        function check_file(file) {
            const white_suffix_file =
                ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.xls', '.xlsx',
                    '.csv', '.ods', '.pdf', '.txt', '.doc', '.docx', '.rtf', '.md', '.pdf',
                    '.odt', '.wps', '.xlsm', '.ppt', '.pptx', '.pps', '.ppsx', '.odp', '.key'];
            let file_split_list = file.split('.')
            let file_suffix = file_split_list[file_split_list.length - 1]
            let target = '.' + file_suffix.toLowerCase()
            let result = white_suffix_file.includes(target); // true
            return result
        };

        // 处理选中的文件
        function handleFiles(files) {
            if (files.length > 1) {
                showNotification('info', '上传文件失败', `请单独上传文件`);
                return;
            }
            if (files.length === 0) return;
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (!check_file(file.name)) {
                    showNotification('info', '文件格式错误', `${file.name} 不支持上传`);
                    continue;
                }

                if (selectedFiles.some(f => f.name === file.name && f.size === file.size)) {
                    showNotification('info', '文件已存在', `"${file.name}" 已在上传列表中`);
                    continue;
                }

                // 添加文件到状态管理
                selectedFiles.push({
                    file: file,
                    status: 'pending',
                    progress: 0
                });

                addFileToUI(file, 'pending');
            }

            updateUploadButtonState();
        }

        // 添加文件到界面
        function addFileToUI(file, status) {
            // 清空空文件列表提示
            if (selectedFiles.length === 1) {
                fileList.innerHTML = '';
            }

            const fileSize = formatFileSize(file.size);
            const fileExtension = getFileExtension(file.name).toLowerCase();
            const fileIcon = getFileIcon(fileExtension);

            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            fileItem.dataset.filename = file.name;

            // 根据状态显示不同的UI
            if (status === 'pending') {
                fileItem.innerHTML = `
                    <div class="flex items-center">
                        <div class="file-icon w-8 h-8 md:w-10 md:h-10 rounded bg-primary/10 flex items-center justify-center mr-3 md:mr-4">
                            <i class="fa ${fileIcon} text-primary"></i>
                        </div>
                        <div>
                            <!-- 修改这里：限制宽度为15个字符并显示省略号 -->
<!--                            <h4 class="font-medium truncate max-w-[18ch]">${file.name}</h4>-->
                                <h4 class="font-medium truncate max-w-[18ch]" title="${file.name}">${file.name}</h4>
                            <p class="text-xs md:text-sm text-gray-500">${fileSize}</p>
                        </div>
                    </div>
                    <div class="flex items-center ml-3">
                        <button class="remove-file btn btn-danger text-xs md:text-sm">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                    `;
            } else if (status === 'uploading') {
                fileItem.innerHTML = `
                        <div class="flex items-center">
                            <div class="file-icon w-8 h-8 md:w-10 md:h-10 rounded bg-primary/10 flex items-center justify-center mr-3 md:mr-4">
                                <i class="fa ${fileIcon} text-primary"></i>
                            </div>
                            <div>
                                 <h4 class="font-medium truncate max-w-xs md:max-w-sm" title="${file.name}">${file.name}</h4>
<!--                                <h4 class="font-medium truncate max-w-[18ch]" title="${file.name}">${file.name}</h4>-->
                                <div class="flex items-center mt-1">
                                    <div class="progress-bar w-24 md:w-32 mr-2"></div>
                                    <span class="upload-progress text-xs md:text-sm text-gray-500">0%</span>
                                </div>
                            </div>
                        </div>
                        <div class="flex items-center ml-3">
                            <button class="cancel-upload btn btn-secondary text-xs md:text-sm">
                                <i class="fa fa-pause"></i>
                            </button>
                        </div>
                    `;
            } else if (status === 'completed') {
                fileItem.innerHTML = `
                    <div class="flex items-center">
                        <div class="file-icon w-8 h-8 md:w-10 md:h-10 rounded bg-success/10 flex items-center justify-center mr-3 md:mr-4">
                            <i class="fa ${fileIcon} text-success"></i>
                        </div>
                        <div>
                            <!-- 限制文件名长度为15个字符，超出显示省略号 -->
                            <h4 class="font-medium truncate max-w-[15ch]" title="${file.name}">${file.name}</h4>
                            <p class="text-xs md:text-sm text-success">上传完成</p>
                        </div>
                    </div>
                    <div class="flex items-center ml-3">
                        <button class="download-file btn btn-success text-xs md:text-sm">
                            <i class="fa fa-download"></i>
                        </button>
                    </div>
                    `;
            }

            fileList.appendChild(fileItem);

            fileItem.querySelector('h4').addEventListener('touchstart', handleTouchStart);
            fileItem.querySelector('h4').addEventListener('touchend', handleTouchEnd);
            fileItem.querySelector('h4').addEventListener('touchcancel', handleTouchCancel);
            fileItem.querySelector('h4').addEventListener('touchmove', handleTouchMove);


            // 根据状态绑定不同事件
            if (status === 'pending') {
                // 绑定删除文件事件
                const removeBtn = fileItem.querySelector('.remove-file');
                removeBtn.addEventListener('click', function () {
                    // 停止事件冒泡
                    // event.stopPropagation();
                    removeFile(file.name);
                });
            } else if (status === 'uploading') {
                // 绑定取消上传事件
                const cancelBtn = fileItem.querySelector('.cancel-upload');
                cancelBtn.addEventListener('click', function () {
                    cancelUpload(file.name);
                });
            } else if (status === 'completed') {
                // 绑定下载文件事件（模拟）
                const downloadBtn = fileItem.querySelector('.download-file');
                downloadBtn.addEventListener('click', function () {
                    showNotification('info', '下载文件', `文件 "${file.name}" 开始下载`);
                });
            }
        }

        function handleTouchStart(event) {
            // 记录触摸开始的时间
            this.touchStartTime = new Date().getTime();
        }

        function handleTouchEnd(event) {
            // 获取触摸开始的时间
            const touchStartTime = this.touchStartTime;
            // 获取当前时间
            const currentTime = new Date().getTime();
            // 计算触摸持续时间
            const duration = currentTime - touchStartTime;

            // 如果持续时间超过指定的阈值（比如500毫秒），则认为是长按

            // 显示文件的完整名称
            showFullNameTooltip(this.title);


            // 清除触摸开始时间，为下一次触摸做准备
            this.touchStartTime = null;
        }

        function handleTouchCancel(event) {
            // 清除触摸开始时间，因为触摸已被取消
            this.touchStartTime = null;
        }

        function handleTouchMove(event) {
            // 如果用户移动了手指，则取消长按操作
            this.touchStartTime = null;
        }

        function showFullNameTooltip(filename) {
            // 这里可以创建并显示一个包含文件名的模态框或工具提示
            // 示例：使用alert()函数简单显示（实际开发中应使用更优雅的方式）
            alert('文件名称: ' + filename);
        }

        // 更新文件状态
        function updateFileStatus(filename, status, progress = 0) {
            const file = selectedFiles.find(f => f.file.name === filename);
            if (!file) return;

            file.status = status;
            file.progress = progress;

            // 更新UI
            const fileItem = Array.from(fileList.querySelectorAll('.file-item')).find(
                item => item.dataset.filename === filename
            );

            if (fileItem) {
                fileList.removeChild(fileItem);
                addFileToUI(file.file, status);

                // 如果是上传中，更新进度条
                if (status === 'uploading') {
                    const progressBar = fileList.querySelector(`[data-filename="${filename}"] .progress-bar`);
                    const progressValue = document.createElement('div');
                    progressValue.className = 'progress-value';
                    progressValue.style.width = `${progress}%`;
                    progressBar.appendChild(progressValue);

                    const progressText = fileList.querySelector(`[data-filename="${filename}"] .upload-progress`);
                    progressText.textContent = `${progress}%`;
                }
            }

            updateUploadButtonState();
        }

        // 删除文件
        function removeFile(filename) {
            selectedFiles = selectedFiles.filter(f => f.file.name !== filename);

            const fileItem = fileList.querySelector(`[data-filename="${filename}"]`);
            if (fileItem) {
                fileItem.classList.add('opacity-0');
                setTimeout(() => {
                    fileItem.remove();
                    if (selectedFiles.length === 0) {
                        fileList.innerHTML = `
                                <div class="text-center py-8 md:py-10 text-gray-400">
                                    <i class="fa fa-file-o text-3xl md:text-4xl mb-2.5 md:mb-3"></i>
                                    <p class="text-sm md:text-base">暂无上传的文件</p>
                                </div>
                            `;
                    }
                    updateUploadButtonState();
                }, 300);
            }
        }

        // 取消上传
        function cancelUpload(filename) {
            removeFile(filename);
            showNotification('info', '已取消', `文件 "${filename}" 已取消上传`);
        }

        // 更新上传按钮状态
        function updateUploadButtonState() {
            // 如果没有待上传文件，禁用上传按钮
            const hasPendingFiles = selectedFiles.some(f => f.status === 'pending');
            uploadFilesBtn.disabled = !hasPendingFiles;

            // 如果有文件正在上传，隐藏上传按钮
            const hasUploadingFiles = selectedFiles.some(f => f.status === 'uploading');
            uploadContainer.style.display = hasUploadingFiles ? 'none' : 'block';
        }

        uploadFilesBtn.addEventListener('click', async function () {
            let file_result = []
            var return_home = false;
            const pendingFiles = selectedFiles.filter(f => f.status === 'pending');

            if (pendingFiles.length === 0) return;
            const uuid = getCookie('uuid');

            // 显示上传中状态
            pendingFiles.forEach(file => {

                updateFileStatus(file.file.name, 'uploading');
            });
            // 逐个上传文件
            for (const fileObj of pendingFiles) {
                try {
                    const file = fileObj.file;
                    const formData = new FormData();
                    formData.append('file', file);
                    if (uuid) {
                        formData.append('uuid', uuid);
                    }
                    // 上传到Odoo服务器
                    // 注意：不要设置Content-Type头，让浏览器自动处理
                    const response = await fetch('/get/upload_file', {
                        method: 'POST',
                        body: formData,
                    });

                    // 检查响应状态
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const result = await response.json();
                    if (result[0].success) {
                        updateFileStatus(file.name, 'completed');
                        return_home = true
                        showNotification('success', '上传成功', `文件 "${file.name}" 已上传`);
                        file_result.push(result[0])

                        // window.history.back();
                    } else {
                        updateFileStatus(file.name, 'pending');
                        return_home = false
                        showNotification('error', '上传失败', result[0].message || '上传过程中发生错误');
                    }
                } catch (error) {
                    updateFileStatus(fileObj.file.name, 'pending');
                    return_home = false
                    showNotification('error', '上传失败', `错误: ${error.message}`);
                }
            }
            // if (return_home) {
            //     wx.miniProgram.postMessage({
            //         data: file_result
            //     })

                setTimeout(() => {
                    wx.miniProgram.navigateBack({})
                }, 1000)
            // }
        })


// 辅助函数：从cookie中获取CSRF令牌
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }



        // 清空文件列表
        clearFilesBtn.addEventListener('click', function () {
            if (selectedFiles.length === 0) return;

            selectedFiles = [];
            fileList.innerHTML = `
                    <div class="text-center py-8 md:py-10 text-gray-400">
                        <i class="fa fa-file-o text-3xl md:text-4xl mb-2.5 md:mb-3"></i>
                        <p class="text-sm md:text-base">暂无上传的文件</p>
                    </div>
                `;

            updateUploadButtonState();
            showNotification('info', '已清空列表', '所有文件已从上传列表中移除');
        });

        // 显示通知
function showNotification(type, title, message) {
    // 设置通知内容
    notificationTitle.textContent = title;
    notificationMessage.textContent = message;
    notification.style.zIndex = '9999';
    // 设置通知图标和颜色
    notificationIcon.className = '';
    notification.classList.remove('bg-success', 'bg-danger', 'bg-info', 'text-success', 'text-danger', 'text-info');
    if (type === 'success') {
        notificationIcon.className = 'fa fa-check-circle text-success';
        notification.classList.add('bg-white', 'text-success');
    } else if (type === 'error') {
        notificationIcon.className = 'fa fa-exclamation-circle text-danger';
        notification.classList.add('bg-white', 'text-danger');
    } else if (type === 'info') {
        notificationIcon.className = 'fa fa-info-circle text-info';
        notification.classList.add('bg-white', 'text-info');
    }

    // 显示通知
    notification.classList.remove('translate-y-20', 'opacity-0');

    // 1.5秒后自动关闭
    setTimeout(hideNotification, 1500);
}

        // 隐藏通知
        function hideNotification() {
            notification.classList.add('translate-y-20', 'opacity-0');
        }

        // 关闭通知按钮
        closeNotification.addEventListener('click', hideNotification);

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';

            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));

            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 获取文件扩展名
        function getFileExtension(filename) {
            return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2);
        }

        // 根据文件扩展名获取图标
        function getFileIcon(extension) {
            const fileIcons = {
                'pdf': 'fa-file-pdf-o',
                'doc': 'fa-file-word-o',
                'docx': 'fa-file-word-o',
                'xls': 'fa-file-excel-o',
                'xlsx': 'fa-file-excel-o',
                'ppt': 'fa-file-powerpoint-o',
                'pptx': 'fa-file-powerpoint-o',
                'jpg': 'fa-file-image-o',
                'jpeg': 'fa-file-image-o',
                'png': 'fa-file-image-o',
                'gif': 'fa-file-image-o',
                'txt': 'fa-file-text-o',
                'zip': 'fa-file-archive-o',
                'rar': 'fa-file-archive-o',
                'mp3': 'fa-file-audio-o',
                'mp4': 'fa-file-video-o',
                'html': 'fa-file-code-o',
                'css': 'fa-file-code-o',
                'js': 'fa-file-code-o',
                'json': 'fa-file-code-o',
                'xml': 'fa-file-code-o',
                'php': 'fa-file-code-o',
                'py': 'fa-file-code-o',
                'java': 'fa-file-code-o',
                'cpp': 'fa-file-code-o',
                'c': 'fa-file-code-o',
                'cs': 'fa-file-code-o',
                'rb': 'fa-file-code-o',
                'sql': 'fa-file-code-o',
                'exe': 'fa-file-o',
                'dll': 'fa-file-o',
                'bat': 'fa-file-o',
                'apk': 'fa-file-o',
                'iso': 'fa-file-o',
                'psd': 'fa-file-image-o',
                'ai': 'fa-file-image-o',
                'eps': 'fa-file-image-o',
                'svg': 'fa-file-image-o',
                'ttf': 'fa-file-font-o',
                'otf': 'fa-file-font-o',
                'woff': 'fa-file-font-o',
                'woff2': 'fa-file-font-o',
                'default': 'fa-file-o'
            };
            return fileIcons[extension] || fileIcons['default'];
        }
    });
</script>
</body>
</html>